package com.lvmama.dashboard.core.aop;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.lvmama.dashboard.exception.ServiceException;
import com.lvmama.dashboard.exception.ValidateException;
import com.lvmama.dashboard.model.rop.AjaxResponse;
import com.lvmama.java.rhino.spark.utils.Constants;

public class ErrorInterceptor extends HandlerInterceptorAdapter {

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		if(ex != null && (ex.getCause() instanceof ValidateException || ex.getCause() instanceof ServiceException)) {
			PrintWriter writer = response.getWriter();
			response.setContentType("application/json;charset=UTF-8");
			AjaxResponse<Object> resp = new AjaxResponse<Object>();
			resp.setCode(Constants.CODE.ERROR.getCode());
			resp.setMessage(ex.getCause().getMessage());
			writer.write(JSONObject.toJSONString(resp));
			writer.flush();
			writer.close();
			return;
		}
		super.afterCompletion(request, response, handler, ex);
	}

}
